package edu.uoc.tds.cliente;


import edu.uoc.tds.bean.Asistente;
import edu.uoc.tds.bean.CentroDocente;
import edu.uoc.tds.bean.Contacto;
import edu.uoc.tds.bean.DatosBancarios;
import edu.uoc.tds.bean.DocumentoIdentificacion;
import edu.uoc.tds.bean.Usuario;
import java.rmi.RemoteException;
import edu.uoc.tds.server.GestorDisco;
import edu.uoc.tds.server.GestorUsuario;
import java.util.logging.Level;
import java.util.logging.Logger;


import javax.swing.*;

import java.awt.Rectangle;
import javax.swing.JOptionPane; 
import javax.swing.JComboBox;
import java.util.*;

import edu.uoc.tds.common.MostrarCombo;
import edu.uoc.tds.common.RemotoInterface;
import edu.uoc.tds.common.UtilLenguaje;
import edu.uoc.tds.common.Utils;
import edu.uoc.tds.common.Variables;

import java.awt.Color;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;





public class PantallaAltaUsuaris extends javax.swing.JPanel {

    private RemotoInterface objServeis = null;
    private static final long serialVersionUID = 1L;
    private JComboBox comboEvento = null;
    private JComboBox comboUniversidad = null;
    private JComboBox comboPais = null;
    private JButton botonGuardar = null;
    private JButton botonCancelar = null;
    private JTextField fechaValor = null;
    private JTextArea descripcion = null;
    private JTextField importe = null;
    private UtilLenguaje txt = null;
    private JLabel labelEvento = null;
    private JLabel labelProveedor = null;
    private JLabel labelConcepto = null;
    private JLabel labelFecha = null;
    private JLabel labelDescripcion = null;
    private JLabel labelImporte = null;
    JScrollPane textScroll=null;


    // Variables Oscar

    // Labels associades a Taula Usuario

    private JLabel labelCodUsuari =null;
    private JLabel labelNom =null;
    private JLabel labelCognoms =null;
    private JLabel labelDataNaixement =null;
    private JLabel labelSexe=null;
    private JLabel labelDocument= null;    
    private JLabel labelContrasenya = null;
    private JLabel labelContrasenyaConfirmacio = null;
    private JLabel labelEstat = null;
    private JLabel labelDataEstatUsuari = null;
    private JLabel labelMotiuEstatUsuari = null;
    private JLabel labelPerfil = null;

    // Labels associades a Taula Contacto

    private JLabel labelAdressa = null;
    private JLabel labelCodiPostal = null;
    private JLabel labelLocalitat = null;
    private JLabel labelPais  = null;
    private JLabel labelEmail = null;
    private JLabel labelWeb = null;
    private JLabel labelTelefon  = null;
    private JLabel labelMotiuEstatContacte = null;
    private JLabel labelDataEstatContacte = null;
    

    // Labels dades bancaries
    private JLabel labelIBAN = null;
    private JLabel labelEntitat = null;
    private JLabel labelOficina = null;
    private JLabel labelDC = null;
    private JLabel labelCompte = null;

    private JTextField codUsuari =null;
    private JTextField nom =null;
    private JTextField cognoms =null;
    private JComboBox  tipusDocument= null;
    private JComboBox  comboSexe = null;
    private JTextField numDocument= null;
    private JFormattedTextField  dataNaixement =null;
    private JPasswordField contrasenya = null;
    private JPasswordField contrasenyaConfirmacio = null;    
    private JRadioButton perfilAdmon = null;
    private JRadioButton perfilSecretaria = null;
    private JRadioButton perfilUsuari = null;

    // camps Text associats a Taula Contacto
    private JTextField adressa = null;
    private JTextField codiPostal = null;
    private JTextField localitat = null;
    private JTextField eMail = null;
    private JTextField web = null;
    private JTextField telefon  = null;


    // camps Associats a Domiciliacio

    private JTextField iban = null;
    private JTextField entitat = null;
    private JTextField oficina = null;
    private JTextField dc = null;
    private JTextField compte  = null;

    
    int estadoRadioButton=0;

    Asistente asistent = null;

    public PantallaAltaUsuaris(RemotoInterface pObjServeis) throws RemoteException {
        super();
        objServeis = pObjServeis;
        initComponents();

    }

     private JComboBox getUniversidad() {

        if (comboUniversidad == null) {
            comboUniversidad = new JComboBox();
            Vector<MostrarCombo> vUniversidad=null;
            try {
                vUniversidad = objServeis.listaUniversidades();

                comboUniversidad = new JComboBox(vUniversidad);
                comboUniversidad.setBounds(new Rectangle(90, 220, 180, 25));
            } catch (Exception eRe) {
                JOptionPane.showMessageDialog(null,
                        txt.getMessage("pantAlta.error.remoto") + "\n" + eRe.getMessage(),
                        txt.getMessage("pantAlta.error"), JOptionPane.ERROR_MESSAGE);

            } 

        }
        return comboUniversidad; 
    }

     private JComboBox getComboPais() {

        if (comboPais == null) {
            comboPais = new JComboBox();
            Vector<MostrarCombo> vPais=null;
            try {
                vPais = objServeis.listaPaises();

                comboPais = new JComboBox(vPais);
                comboPais.setBounds(new Rectangle(0, 20, 275, 25));
            } catch (Exception eRe) {
                JOptionPane.showMessageDialog(null,
                        txt.getMessage("pantAlta.error.remoto") + "\n" + eRe.getMessage(),
                        txt.getMessage("pantAlta.error"), JOptionPane.ERROR_MESSAGE);
            }
        }
        return comboPais;
    }

    private void initComponents() {


        this.setLayout(null);
        this.setBounds(new Rectangle(0, 0, 800, 300));
       
        labelNom = new JLabel();
        labelNom.setBounds(new Rectangle(20, 20, 50, 20));
        labelNom.setText(txt.getMessage("pantUsuari.label.nom"));
        this.add(labelNom);

        nom = new JTextField(20);
        nom.setBounds(new Rectangle(70, 20, 80, 20));
        this.add(nom);

        labelCognoms = new JLabel();
        labelCognoms.setBounds(new Rectangle(170, 20, 60, 20));
        labelCognoms.setText(txt.getMessage("pantUsuari.label.cognoms"));
        this.add(labelCognoms);

        cognoms = new JTextField(60);
        cognoms.setBounds(new Rectangle(240, 20, 150, 20));
        this.add(cognoms);

        labelCodUsuari = new JLabel();
        labelCodUsuari.setBounds(new Rectangle(400, 20, 100, 20));
        labelCodUsuari.setText(txt.getMessage("pantUsuari.label.codUsuari"));
        this.add(labelCodUsuari);

        codUsuari = new JTextField(20);
        codUsuari.setBounds(new Rectangle(490, 20, 90, 20));
        codUsuari.setEnabled(false);
        codUsuari.setBackground(Color.LIGHT_GRAY);
        this.add(codUsuari);

        labelDocument = new JLabel();
        labelDocument.setBounds(new Rectangle(20, 45, 100, 20));
        labelDocument.setText(txt.getMessage("pantUsuari.label.document"));
        this.add(labelDocument);

        //tipusDocument = getTipusDocument();
        this.add(getTipusDocument(),null);

        numDocument = new JTextField(10);
        numDocument.setBounds(new Rectangle(195, 45, 100, 20));
        this.add(numDocument);

        labelDataNaixement = new JLabel();
        labelDataNaixement.setBounds(new Rectangle(300, 45, 120, 20));
        labelDataNaixement.setText(txt.getMessage("pantUsuari.label.dataNaixement"));
        this.add(labelDataNaixement);

        dataNaixement = new JFormattedTextField(DateFormat.getDateInstance(DateFormat.SHORT));
        dataNaixement.setBounds(new Rectangle(405, 45, 70, 20));
        this.add(dataNaixement);

        labelSexe = new JLabel();
        labelSexe.setBounds(new Rectangle(480, 45, 30, 20));
        labelSexe.setText(txt.getMessage("pantUsuari.label.sexe"));
        this.add(labelSexe);

        this.add(getSexe());


        labelContrasenya = new JLabel();
        labelContrasenya.setBounds(new Rectangle(20, 70, 100, 20));
        labelContrasenya.setText(txt.getMessage("pantUsuari.label.contrasenya"));
        this.add(labelContrasenya);

        contrasenya = new JPasswordField(10);
        contrasenya.setBounds(new Rectangle(100, 70, 80, 20));
        this.add(contrasenya);

        labelContrasenyaConfirmacio = new JLabel();
        labelContrasenyaConfirmacio.setBounds(new Rectangle(200, 70, 160, 20));
        labelContrasenyaConfirmacio.setText(txt.getMessage("pantUsuari.label.contrasenyaConfirmacio"));
        this.add(labelContrasenyaConfirmacio);

        contrasenyaConfirmacio = new JPasswordField(10);
        contrasenyaConfirmacio.setBounds(new Rectangle(370, 70, 80, 20));
        this.add(contrasenyaConfirmacio);

        perfilAdmon = new JRadioButton("Administrador");
        perfilAdmon.setBounds(new Rectangle(120, 105, 130, 20));
        perfilAdmon.setMnemonic(1);
        //perfilAdmon.setActionCommand("NO");
        perfilAdmon.setSelected(true);

        perfilSecretaria = new JRadioButton("Secretaria");
        perfilSecretaria.setBounds(new Rectangle(260, 105, 100, 20));
        perfilSecretaria.setMnemonic(2);
        //perfilSecretaria.setActionCommand("SI");

        perfilUsuari = new JRadioButton("Usuari");
        perfilUsuari.setBounds(new Rectangle(370, 105, 70, 20));
        perfilUsuari.setMnemonic(2);

        ButtonGroup group = new ButtonGroup();
        group.add(perfilAdmon);
        group.add(perfilSecretaria);
        group.add(perfilUsuari);

        this.add(perfilAdmon);
        this.add(perfilSecretaria);
        this.add(perfilUsuari);

        perfilAdmon.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                estadoRadioButton=1;
                actDesDatosContacto(false);
                actDesDatosBancarios(false);
            }
        });

        perfilSecretaria.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                estadoRadioButton=2;
                actDesDatosContacto(true);
                actDesDatosBancarios(false);
            }
        });

        perfilUsuari.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                estadoRadioButton=3;
                actDesDatosContacto(true);
                actDesDatosBancarios(true);
            }
        });

        labelPais = new JLabel();
        labelPais.setBounds(new Rectangle(20, 145, 100, 20));
        labelPais.setText(txt.getMessage("pantUsuari.label.pais"));
        this.add(labelPais);

        this.add(getPaises(), null);

        labelCodiPostal = new JLabel();
        labelCodiPostal.setBounds(new Rectangle(190, 145, 100, 20));
        labelCodiPostal.setText(txt.getMessage("pantUsuari.label.cp"));
        this.add(labelCodiPostal);

        codiPostal = new JTextField(60);
        codiPostal.setBounds(new Rectangle(290, 145, 80, 20));
        codiPostal.setEnabled(false);
        codiPostal.setBackground(Color.LIGHT_GRAY);
        this.add(codiPostal);

        labelLocalitat = new JLabel();
        labelLocalitat.setBounds(new Rectangle(380, 145, 70, 20));
        labelLocalitat.setText(txt.getMessage("pantUsuari.label.localitat"));
        this.add(labelLocalitat);

        localitat = new JTextField(60);
        localitat.setBounds(new Rectangle(440, 145, 130, 20));
        localitat.setEnabled(false);
        localitat.setBackground(Color.LIGHT_GRAY);
        this.add(localitat);

        labelAdressa = new JLabel();
        labelAdressa.setBounds(new Rectangle(20, 170, 100, 20));
        labelAdressa.setText(txt.getMessage("pantUsuari.label.adressa"));
        this.add(labelAdressa);

        adressa = new JTextField(60);
        adressa.setBounds(new Rectangle(80, 170, 290, 20));
        adressa.setEnabled(false);
        adressa.setBackground(Color.LIGHT_GRAY);
        this.add(adressa);

        labelTelefon = new JLabel();
        labelTelefon.setBounds(new Rectangle(380, 170, 70, 20));
        labelTelefon.setText(txt.getMessage("pantUsuari.label.telefon"));
        this.add(labelTelefon);

        telefon = new JTextField(60);
        telefon.setBounds(new Rectangle(440, 170, 130, 20));
        telefon.setEnabled(false);
        telefon.setBackground(Color.LIGHT_GRAY);
        this.add(telefon);

        labelWeb = new JLabel();
        labelWeb.setBounds(new Rectangle(20, 195, 50, 20));
        labelWeb.setText(txt.getMessage("pantUsuari.label.web"));
        this.add(labelWeb);

        web = new JTextField(60);
        web.setBounds(new Rectangle(80, 195, 190, 20));
        web.setEnabled(false);
        web.setBackground(Color.LIGHT_GRAY);
        this.add(web);

        labelEmail = new JLabel();
        labelEmail.setBounds(new Rectangle(280, 195, 60, 20));
        labelEmail.setText(txt.getMessage("pantUsuari.label.eMail"));
        this.add(labelEmail);

        eMail = new JTextField(60);
        eMail.setBounds(new Rectangle(350, 195, 220, 20));
        eMail.setEnabled(false);
        eMail.setBackground(Color.LIGHT_GRAY);
        this.add(eMail);

        labelPais = new JLabel();
        labelPais.setBounds(new Rectangle(20, 220, 100, 20));
        labelPais.setText(txt.getMessage("pantUsuari.label.universitat"));
        this.add(labelPais);

        this.add(getUniversidad(), null);


        labelIBAN = new JLabel();
        labelIBAN.setBounds(new Rectangle(60, 255, 100, 20));
        labelIBAN.setText(txt.getMessage("pantUsuari.label.iban"));
        this.add(labelIBAN);

        labelEntitat = new JLabel();
        labelEntitat.setBounds(new Rectangle(175, 255, 100, 20));
        labelEntitat.setText(txt.getMessage("pantUsuari.label.entitat"));
        this.add(labelEntitat);

        labelOficina = new JLabel();
        labelOficina.setBounds(new Rectangle(275, 255, 100, 20));
        labelOficina.setText(txt.getMessage("pantUsuari.label.oficina"));
        this.add(labelOficina);

        labelDC = new JLabel();
        labelDC.setBounds(new Rectangle(390, 255, 100, 20));
        labelDC.setText(txt.getMessage("pantUsuari.label.dc"));
        this.add(labelDC);

        labelCompte = new JLabel();
        labelCompte.setBounds(new Rectangle(460, 255, 100, 20));
        labelCompte.setText(txt.getMessage("pantUsuari.label.compte"));
        this.add(labelCompte);

        iban = new JTextField(60);
        iban.setBounds(new Rectangle(50, 275, 90, 20));
        iban.setEnabled(false);
        iban.setBackground(Color.LIGHT_GRAY);
        this.add(iban);

        entitat = new JTextField(60);
        entitat.setBounds(new Rectangle(150, 275, 90, 20));
        entitat.setEnabled(false);
        entitat.setBackground(Color.LIGHT_GRAY);
        this.add(entitat);

        oficina = new JTextField(60);
        oficina.setBounds(new Rectangle(250, 275, 90, 20));
        oficina.setEnabled(false);
        oficina.setBackground(Color.LIGHT_GRAY);
        this.add(oficina);

        dc = new JTextField(60);
        dc.setBounds(new Rectangle(350, 275, 90, 20));
        dc.setEnabled(false);
        dc.setBackground(Color.LIGHT_GRAY);
        this.add(dc);

        compte = new JTextField(60);
        compte.setBounds(new Rectangle(450, 275, 90, 20));
        compte.setEnabled(false);
        compte.setBackground(Color.LIGHT_GRAY);
        this.add(compte);

        this.add(getBotonCancelar(), null);
        this.add(getBotonGuardar(), null);
    }

    private JButton getBotonGuardar() {



        if (botonGuardar == null) {
            botonGuardar = new JButton();
            botonGuardar.setBounds(new Rectangle(290, 310, 270, 30));
            botonGuardar.setText(txt.getMessage("pantAlta.boton.guardar"));
            botonGuardar.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    //almacenarDatos();
                    try {
                        String cod = codUsuari.getText();
                        String nombre = nom.getText();
                        String apellidos = cognoms.getText();
                        String sexo = comboSexe.getSelectedItem().toString();
                        String fechaNac = dataNaixement.getText().toString();
                        Date fechaAlta = null;
                        CentroDocente centroDocente = new CentroDocente();
                        DocumentoIdentificacion documentoIdentificacion = new DocumentoIdentificacion();
                        Contacto contacto = new Contacto();

                        if (validarDatos()){
                            asistent = new Asistente(cod, nombre, apellidos, sexo, (Date) null, (Date) null, null, "ADM", null, null,  1, null, 1);
                            objServeis.insertarAsistente(asistent);
                        }
                    } catch (RemoteException ex) {
                        Logger.getLogger(PantallaAltaUsuaris.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }
            });
        }
        return botonGuardar;
    }

    private JButton getBotonCancelar() {
        if (botonCancelar == null) {
            botonCancelar = new JButton();
            botonCancelar.setBounds(new Rectangle(10, 310, 270, 30));
            botonCancelar.setText(txt.getMessage("pantAlta.boton.cancelar"));
            botonCancelar.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        PantallaAltaUsuaris.this.setVisible(false);

                    } catch (Throwable e1) {
                        JOptionPane.showMessageDialog(null,
                                txt.getMessage("pantAlta.cancelar.err") + "\n" + e1.getMessage(),
                                txt.getMessage("pantAlta.cancelar.title.err"), JOptionPane.ERROR_MESSAGE);
                    }
                }
            });
        }
        return botonCancelar;
    }


    private JComboBox getTipusDocument() {

        if (tipusDocument == null) {
            tipusDocument = new JComboBox();
            Vector<MostrarCombo> vTipoDocumento;
            try {
               vTipoDocumento = objServeis.listaTipoDoc();
                tipusDocument = new JComboBox(vTipoDocumento);
                tipusDocument.setBounds(new Rectangle(90, 45, 100, 20));
            } catch (RemoteException eRe) {
                JOptionPane.showMessageDialog(null,
                        txt.getMessage("pantAlta.error.remoto") + "\n" + eRe.getMessage(),
                        txt.getMessage("pantAlta.error"), JOptionPane.ERROR_MESSAGE);

            }

        }
        return tipusDocument;
    }

        private JComboBox getPaises() {

        if (comboPais == null) {
            comboPais = new JComboBox();
            Vector<MostrarCombo> vPaises;
            try {
               vPaises = objServeis.listaPaises();
                comboPais = new JComboBox(vPaises);
                comboPais.setBounds(new Rectangle(80, 145, 100, 20));
                comboPais.setEnabled(false);
            } catch (RemoteException eRe) {
                JOptionPane.showMessageDialog(null,
                        txt.getMessage("pantAlta.error.remoto") + "\n" + eRe.getMessage(),
                        txt.getMessage("pantAlta.error"), JOptionPane.ERROR_MESSAGE);
            }
        }
        return comboPais;
    }

    private JComboBox getSexe() {

        if (comboSexe == null) {
            comboSexe = new JComboBox();

        comboSexe.removeAllItems();
        comboSexe.addItem(txt.getMessage("cbo.Sexo.hombre"));
        comboSexe.addItem(txt.getMessage("cbo.Sexo.mujer"));
        comboSexe.setBounds(new Rectangle(510, 45, 70, 20));

        }
        return comboSexe;
    }



    private void actDesDatosContacto (boolean estat) {

        Color color = null;

        if (!estat) {
            color = Color.LIGHT_GRAY;
        } else  {
            color = Color.WHITE;
        }
        actDesCampo(this.adressa, estat);
        actDesCampo(this.codiPostal, estat);
        actDesCampo(this.comboPais, estat);
        actDesCampo(this.localitat, estat);
        actDesCampo(this.telefon, estat);
        actDesCampo(this.web, estat);
        actDesCampo(this.eMail, estat);
    }

   private void actDesDatosBancarios (boolean estat) {

        Color color = null;

        if (!estat) {
            color = Color.LIGHT_GRAY;
        } else  {
            color = Color.WHITE;
        }
        actDesCampo(this.iban, estat);
        actDesCampo(this.entitat, estat);
        actDesCampo(this.oficina, estat);
        actDesCampo(this.dc, estat);
        actDesCampo(this.compte, estat);
    }
    private void actDesCampo (JTextField Campo, boolean Activo) {

        Color color = null;

        if (Activo) {
             color = Color.WHITE;
        } else {
            color = Color.LIGHT_GRAY;
        }

        Campo.setBackground(color);
        Campo.setEnabled(Activo);
    }

    private void actDesCampo (JComboBox Campo, boolean Activo) {

        Color color = null;

        if (Activo) {
             color = Color.WHITE;
        } else {
            color = Color.LIGHT_GRAY;
        }

        Campo.setBackground(color);
        Campo.setEnabled(Activo);
    }



        private boolean validarDatos () {
            
            boolean valido = true;
            String cadena = "";


            String sexo = comboSexe.getSelectedItem().toString();
            String fechaNac = dataNaixement.getText().toString();

            Date fechaAlta = null;
            CentroDocente centroDocente = new CentroDocente();
            DocumentoIdentificacion documentoIdentificacion = new DocumentoIdentificacion();
            Contacto contacto = new Contacto();
            DatosBancarios datosBancarios = new DatosBancarios(iban.getText(), entitat.getText(),
                    oficina.getText(), dc.getText(), compte.getText(), null, 0);

            if (isEmpty(nom.getText())) {
                cadena = txt.getMessage("pU.error.nombre") + "\n" ;
            }

            if (isEmpty(cognoms.getText())) {
                cadena += txt.getMessage("pU.error.apellidos" + "\n");
            }

            if (!isDate(fechaNac) || isEmpty(fechaNac)){
                cadena += txt.getMessage("pU.error.fechaNacimiento" + "\n");
            }

            // Dades Bancaries
            if (isEmpty(iban.getText()) || isEmpty(entitat.getText()) || isEmpty(oficina.getText()) ||
                    isEmpty(dc.getText()) || isEmpty(compte.getText())) {
                cadena += txt.getMessage("pU.error.dadesBancaries" + "\n");
            }

            if (!isEmpty(cadena)) {
                JOptionPane.showMessageDialog(null,cadena);
                valido = false;
            }

            return valido;
        }

    public static boolean isEmpty(Object object) {
        if (object == null || object.toString().trim().equals("")) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isDate(String date) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
            sdf.setLenient(false);
            sdf.parse(date);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}